//
//  SEGDailyContentViewModel.m
//  Commom
//
//  Created by 梁学彰 on 2020/6/15.
//

#import "SEGDailyContentViewModel.h"

@implementation SEGDailyContentViewModel
#pragma mark - life cycle
- (instancetype)initWithTopicId:(NSString *)topicId {
    if (self = [super init]) {
        _topicId = topicId;
        [self initData];
        [self seg_createDataCommand];
    }
    return self;
}
#pragma mark - init
- (void)initData {
    self.currentIndex = 0;
    self.pageNo = 1;
    self.totalPages = 1;
}

#pragma mark - send request
- (void)seg_createDataCommand {
    @weakify(self);
    self.dataCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            @strongify(self);
            if (self.pageNo > self.totalPages) {
                [subscriber sendCompleted];
                return nil;
            }
            
            [self.sharedNewManager requestDailyContentArrayWithPageNo:[NSString stringWithFormat:@"%ld",(unsigned long)self.pageNo] pageLimit:@"10" topicId:self.topicId finished:^(BOOL isSuccessed, NSString *codeType, NSString *errorMessage) {
                
                if (isSuccessed) {
                    self.dataSource = self.sharedNewManager.recommendContentArray;
                    if (self.sharedNewManager.recommendContentArray.count > 0) {
                        self.totalPages = self.sharedNewManager.dailyContentTotalPages;
                        self.totalCount = self.sharedNewManager.dailyContentTotalCount;
                    }
                    [subscriber sendNext:nil];
                }else {
                    [subscriber sendError:nil];
                }
                [subscriber sendCompleted];
            }];
            return nil;
        }];
    }];
}
#pragma mark - custom delegate

#pragma mark - system delegate

#pragma mark - event response

#pragma mark - private methods

#pragma mark - setter and getter
- (SEGSharedNewManager *)sharedNewManager
{
    if (!_sharedNewManager) {
        _sharedNewManager = [[SEGSharedNewManager alloc] init];
    }
    return _sharedNewManager;
}
@end
